import request from '../../utils/request'
import { showError } from '../../utils/util'

Page({
    data: {
        postList: [],
        currentCategory: '',
        page: 1,
        size: 10,
        hasMore: true,
        loading: false
    },

    onLoad() {
        this.loadPosts()
    },

    onPullDownRefresh() {
        this.setData({
            page: 1,
            postList: [],
            hasMore: true
        })
        this.loadPosts().finally(() => {
            wx.stopPullDownRefresh()
        })
    },

    onReachBottom() {
        if (this.data.hasMore && !this.data.loading) {
            this.loadPosts()
        }
    },

    async loadPosts() {
        if (this.data.loading) return

        this.setData({ loading: true })

        try {
            const params = {
                page: this.data.page,
                size: this.data.size
            }

            let posts = []
            if (this.data.currentCategory) {
                posts = await request.get(`/posts/category/${this.data.currentCategory}`)
            } else {
                posts = await request.get('/posts', params)
            }

            // 检查点赞状态
            const postsWithLikeStatus = await Promise.all(
                posts.map(async post => {
                    try {
                        const likeStatus = await request.get('/team/check-like', {
                            postId: post.id,
                            userId: wx.getStorageSync('userId') || 1
                        })
                        return {
                            ...post,
                            isLiked: likeStatus.isLiked
                        }
                    } catch (error) {
                        return { ...post, isLiked: false }
                    }
                })
            )

            if (posts.length < this.data.size) {
                this.setData({ hasMore: false })
            }

            this.setData({
                postList: [...this.data.postList, ...postsWithLikeStatus],
                page: this.data.page + 1
            })
        } catch (error) {
            console.error('加载帖子失败:', error)
            showError('加载失败')
        } finally {
            this.setData({ loading: false })
        }
    },

    onCategoryChange(e) {
        const category = e.currentTarget.dataset.category
        this.setData({
            currentCategory: category,
            page: 1,
            postList: [],
            hasMore: true
        })
        this.loadPosts()
    },

    onLikeChange(e) {
        const { postId, isLiked, likeCount } = e.detail
        const postList = this.data.postList.map(post => {
            if (post.id === postId) {
                return {
                    ...post,
                    isLiked,
                    likeCount
                }
            }
            return post
        })
        this.setData({ postList })
    },

    onCreatePost() {
        wx.navigateTo({
            url: '/pages/create-post/create-post'
        })
    }
})